<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <!-- 1. 污染源名称 -->
        <el-form-item label="污染源名称：">
          <el-input
            v-model="queryParams.sourceName"
            placeholder="请输入污染源名称"
            style="width: 180px"
          />
        </el-form-item>
        <!-- 2. 行政区划 -->
        <el-form-item label="行政区划：" prop="countycode">
          <el-select
            v-model="queryParams.countycode"
            placeholder="请选择行政区划"
            style="width: 180px"
          >
            <el-option
              v-for="item in regionList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 3. 是否涉水污染源 -->
        <el-form-item label="是否涉水污染源：" prop="waterrelate">
          <el-select
            v-model="queryParams.waterrelate"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- 4. 是否在线监测 -->
        <el-form-item label="是否在线监测：" prop="isonlinemonitoringent">
          <el-select
            v-model="queryParams.isonlinemonitoringent"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- 5. 是否污水处理厂 -->
        <el-form-item label="是否污水处理厂：" prop="issewagefarm">
          <el-select
            v-model="queryParams.issewagefarm"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- 6. 污染类型 -->
        <el-form-item label="污染类型：" prop="enterprisetype">
          <el-select
            v-model="queryParams.enterprisetype"
            placeholder="请选择污染类型"
            style="width: 180px"
          >
            <el-option
              v-for="item in dict.type.sys_pollutions_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 7. 排污许可证 -->
        <el-form-item label="排污许可证：" prop="outpermitnb">
          <el-input
            v-model="queryParams.outpermitnb"
            placeholder="请输入排污许可证"
            style="width: 180px"
          />
        </el-form-item>
        <!-- 8. 统一社会信用代码 -->
        <el-form-item label="统一社会信用代码：" prop="socialcode">
          <el-input
            v-model="queryParams.socialcode"
            placeholder="请输入统一社会信用代码"
            style="width: 180px"
          />
        </el-form-item>
        <!-- 9. 查询/重置按钮组 -->
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
            style="padding: 10px"
            >查询</el-button
          >
          <el-button @click="resetQuery" style="padding: 10px">
            <i class="iconfont icon-saoba"></i>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="pageContent">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:user:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
            v-hasPermi="['system:user:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:user:export']"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格：添加ref属性用于直接获取选中行 -->
      <el-table
        ref="selectTable"
        id="selectTable"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="pollutename"
          label="污染源名称"
        ></el-table-column>
        <el-table-column prop="socialcode" label="统一社会信用代码" />
        <el-table-column prop="county" label="行政区划"></el-table-column>
        <el-table-column
          prop="industrytypecode"
          label="行业类别"
        ></el-table-column>
        <el-table-column prop="lawperson" label="法定代表人"></el-table-column>
        <el-table-column
          prop="outpermitnb"
          label="排污许可证编号"
        ></el-table-column>
        <el-table-column
          prop="rivername"
          label="污水受纳水体"
        ></el-table-column>
        <el-table-column prop="destination" label="污水去向"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button type="text" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/修改共用弹框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="污染源名称" prop="pollutename">
              <el-input
                v-model="form.pollutename"
                placeholder="请输入污染源名称"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="socialcode">
              <el-input
                v-model="form.socialcode"
                placeholder="请输入统一社会信用代码"
                maxlength="18"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="行政区划" prop="county">
              <el-select
                v-model="form.county"
                placeholder="请选择行政区划"
                style="width: 100%"
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行业类别" prop="industrytypecode">
              <el-select
                v-model="form.industrytypecode"
                placeholder="请选择所属行业"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.industry_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="法定代表人" prop="lawperson">
              <el-input
                v-model="form.lawperson"
                placeholder="请输入法定代表人"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排污许可证编号" prop="outpermitnb">
              <el-input
                v-model="form.outpermitnb"
                placeholder="请输入排污许可证编号"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <!-- 污水受纳水体：固定riverid且禁止修改 -->
            <el-form-item label="污水受纳水体" prop="riverid">
              <el-select
                v-model="form.riverid"
                placeholder="请选择污水受纳水体"
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="item in riverList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="污水去向" prop="destination">
              <el-input
                v-model="form.destination"
                placeholder="请输入污水去向"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 隐藏的主键ID -->
        <el-form-item v-if="false" prop="id">
          <el-input v-model="form.id" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tableToExcel from "@/utils/tableToExcel";
import {
  getPollutionList,
  editPollution,
  deletePollution,
  addPollution,
} from "@/api/traceability";
import { getRegionList } from "@/api/dataResources/monitorData/region.js";
import { getRiverSelect } from "@/api/dataResources/monitorData/section.js";

export default {
  name: "PollutionSourceManage",
  dicts: ["sys_pollutions_type", "industry_type"],
  data() {
    return {
      tableHeight: window.innerHeight - 300,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sourceName: "",
        countycode: "",
        waterrelate: "",
        isonlinemonitoringent: "",
        issewagefarm: "",
        enterprisetype: "",
        outpermitnb: "",
        socialcode: "",
      },
      tableData: [],
      open: false,
      title: "",
      form: {
        id: "",
        pollutename: "",
        socialcode: "",
        county: "",
        industrytypecode: "",
        lawperson: "",
        outpermitnb: "",
        riverid: "7c816e5e-11bb-470e-8a42-82df3f49eb09", // 固定riverid
        destination: "",
      },
      rules: {
        pollutename: [
          { required: true, message: "污染源名称不能为空", trigger: "blur" },
        ],
        socialcode: [
          {
            required: true,
            message: "统一社会信用代码不能为空",
            trigger: "blur",
          },
          {
            pattern: /^[0-9A-HJ-NPQRTUWXY]{18}$/,
            message: "请输入正确的统一社会信用代码",
            trigger: "blur",
          },
        ],
        county: [
          { required: true, message: "行政区划不能为空", trigger: "blur" },
        ],
        industrytypecode: [
          { required: true, message: "行业类别不能为空", trigger: "blur" },
        ],
        lawperson: [
          { required: true, message: "法定代表人不能为空", trigger: "blur" },
        ],
        outpermitnb: [
          {
            required: true,
            message: "排污许可证编号不能为空",
            trigger: "blur",
          },
        ],
        riverid: [
          { required: true, message: "污水受纳水体不能为空", trigger: "blur" },
        ],
        destination: [
          { required: true, message: "污水去向不能为空", trigger: "blur" },
        ],
      },
      regionList: [],
      riverList: [],
      selectedIds: [], // 存储选中的ID数组
    };
  },
  created() {
    this.getRegionList();
    this.getsshl();
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 获取行政区划列表
    async getRegionList() {
      const res = await getRegionList();
      if (res.code === 200) {
        this.regionList = res.rows;
      }
    },
    // 获取河流列表（用于下拉框展示）
    getsshl() {
      getRiverSelect().then((response) => {
        this.riverList = response.data.map((item) => ({
          value: item.id,
          label: item.rivername,
        }));
      });
    },
    // 查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置查询表单
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sourceName: "",
        countycode: "",
        waterrelate: "",
        isonlinemonitoringent: "",
        issewagefarm: "",
        enterprisetype: "",
        outpermitnb: "",
        socialcode: "",
      };
    },
    // 获取污染源列表
    getList() {
      const query = { ...this.queryParams };
      query.riverid = "7c816e5e-11bb-470e-8a42-82df3f49eb09"; // 固定过滤条件

      getPollutionList(query)
        .then((res) => {
          if (res.code === 200) {
            this.tableData = res.rows || [];
          } else {
            this.$modal.msgError("获取数据失败");
          }
        })
        .catch(() => {
          this.$modal.msgError("获取数据失败");
        });
    },
    // 表格选中事件：实时同步选中ID
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id).filter((id) => id);
    },
    // 新增按钮
    handleAdd() {
      this.reset();
      this.form.riverid = "7c816e5e-11bb-470e-8a42-82df3f49eb09";
      this.open = true;
      this.title = "新增污染源信息";
    },
    // 单行修改
    handleEdit(row) {
      this.form = {
        ...row,
        riverid: "7c816e5e-11bb-470e-8a42-82df3f49eb09",
      };
      this.open = true;
      this.title = "修改污染源信息";
    },
    // 删除（支持批量和单行）- 优化后版本
    handleDelete(row) {
      let ids = [];
      let names = [];

      if (row && row.id) {
        // 单行删除
        ids = [row.id];
        names = [row.pollutename || "未知污染源"];
      } else {
        // 批量删除：直接从表格获取选中行（解决同步问题）
        const selectedRows = this.$refs.selectTable?.selection || [];
        if (selectedRows.length === 0) {
          this.$modal.msgError("请先勾选要删除的污染源数据！");
          return;
        }
        ids = selectedRows.map((item) => item.id);
        names = selectedRows.map((item) => item.pollutename || "未知污染源");
      }

      // 优化提示文案（处理名称过长情况）
      const confirmText = row
        ? `是否确认删除污染源"${names[0]}"？删除后不可恢复！`
        : `是否确认删除选中的${names.length}个污染源（${
            names.length > 5
              ? names.slice(0, 5).join("、") + "等"
              : names.join("、")
          }）？删除后不可恢复！`;

      this.$modal
        .confirm(confirmText)
        .then(() => deletePollution(ids.join(",")))
        .then(() => {
          this.getList();
          this.selectedIds = [];
          this.$refs.selectTable?.clearSelection(); // 清空表格勾选状态
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 导出
    handleExport() {
      tableToExcel.getExcel("#selectTable", "废水污染源排放清单");
    },
    // 表单重置
    reset() {
      this.form = {
        id: "",
        pollutename: "",
        socialcode: "",
        county: "",
        industrytypecode: "",
        lawperson: "",
        outpermitnb: "",
        riverid: "7c816e5e-11bb-470e-8a42-82df3f49eb09",
        destination: "",
      };
      this.$refs.form && this.$refs.form.resetFields();
    },
    // 提交表单（新增/修改）
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const isEdit = !!this.form.id;
          const requestFn = isEdit ? editPollution : addPollution;
          const successMsg = isEdit ? "修改成功" : "新增成功";

          const submitData = {
            ...this.form,
            riverid: "7c816e5e-11bb-470e-8a42-82df3f49eb09",
          };

          requestFn(submitData)
            .then((response) => {
              if (response.code === 200) {
                this.$modal.msgSuccess(successMsg);
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError(
                  response.msg || `${isEdit ? "修改" : "新增"}失败`
                );
              }
            })
            .catch(() => {
              this.$modal.msgError(`${isEdit ? "修改" : "新增"}失败`);
            });
        }
      });
    },
    // 取消弹窗
    cancel() {
      this.open = false;
      this.reset();
    },
  },
};
</script>
<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 10px 0 10px 10px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .times {
      .el-form-item__content {
        width: 250px;
      }
    }

    .el-form-item__content {
      min-width: 200px;
    }

    .searchBtnBox {
      display: inline-block;
      margin: 20px 0 20px 20px;
    }
  }

  .pageContent {
    .tabs-list {
      padding-top: 10px;
    }

    .el-tabs__header {
      background: #fff;
    }

    .el-tabs__item {
      border: 1px solid #eee;
      margin: 0;
      border-left: 0;
      background: #fafbfc;
      color: #000;
    }

    .el-tabs__item:first-child {
      margin-left: 20px;
      border-left: 1px solid #eee;
    }

    .is-active {
      border-bottom: 0 !important;
      background: #fff;
      color: #307eff;
    }
  }

  .anjian label {
    padding: 0 !important;
    width: 100px !important;
  }

  .queryForm .el-checkbox {
    margin-right: 10px !important;
    width: auto !important;
  }

  .iszgfc .el-form-item__content {
    width: 120px;
  }
}

.titleBox {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dfe4ed;
  margin: 0 20px 20px 20px;
  position: relative;
  &::before {
    display: block;
    content: "";
    width: 3px;
    height: 16px;
    background: #307eff;
  }
  .title {
    font-size: 16px;
    color: #000;
    position: absolute;
    left: 10px;
    font-weight: 500;
  }
  .more {
    font-size: 16px;
    color: #999;
    cursor: pointer;
  }
}
</style>
